package com.ruoyi.individual.service.impl;

import com.ruoyi.book.domain.Book;
import com.ruoyi.book.mapper.BookMapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.individual.service.IBookPrivateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 共享图书Service业务层处理
 *
 * @author yaohui
 * @date 2024-04-10
 */
@Service
public class BookPrivateServiceImpl implements IBookPrivateService {
    @Autowired
    private BookMapper bookMapper;

    /**
     * 判断书本编号是否唯一
     *
     * @param num 书本编号
     * @return 共享图书
     */
    @Override
    public Book checkBookNumUnique(String num) {
        return bookMapper.checkBookNumUnique(num);
    }

    /**
     * 查询共享图书
     *
     * @param id 共享图书主键
     * @return 共享图书
     */
    @Override
    public Book selectBookPrivateById(Long id) {
        return bookMapper.selectBookById(id);
    }

    /**
     * 查询共享图书列表
     *
     * @param book 图书
     * @return 共享图书
     */
    @Override
    public List<Book> selectBookPrivateList(Book book, String username) {
        return bookMapper.selectBookPrivateList(book, username);
    }

    /**
     * 新增共享图书
     *
     * @param book 共享图书
     * @return 结果
     */
    @Override
    public int insertBookPrivate(Book book) {
        //判断图书编号是否唯一
        Book bookPrivate1 = bookMapper.checkBookNumUnique(book.getNum());
        if (Objects.nonNull(bookPrivate1)) {
            throw new ServiceException("图书编号已存在");
        }
        //状态设置为在馆
        book.setState("0");
        //增添
        return bookMapper.insertBook(book);
    }

    /**
     * 修改共享图书
     *
     * @param book 共享图书
     * @return 结果
     */
    @Override
    public int updateBookPrivate(Book book) {
        //判断图书的状态，若图书状态为已借出，则不能修改
        String state = bookMapper.selectBookById(book.getId()).getState();
        if (!StringUtils.equals(state, "0")) {
            throw new RuntimeException("图书状态为已借出，不能修改");
        }
        book.setUpdateTime(DateUtils.getNowDate());
        return bookMapper.updateBook(book);
    }

    /**
     * 批量删除共享图书
     *
     * @param ids 需要删除的共享图书主键
     * @return 结果
     */
    @Override
    public int deleteBookPrivateByIds(Long[] ids) {
        return bookMapper.deleteBookByIds(ids);
    }

    /**
     * 删除共享图书信息
     *
     * @param id 共享图书主键
     * @return 结果
     */
    @Override
    public int deleteBookPrivateById(Long id) {
        return bookMapper.deleteBookById(id);
    }
}
